package com.kunbo.offer.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kunbo.offer.dao.FanBaseParameterDao;
import com.kunbo.offer.dao.ProductMixDao;
import com.kunbo.offer.entity.FanBaseParameter;
import com.kunbo.offer.entity.ProductMix;
import com.kunbo.offer.service.ProductMixService;
@Service
public class ProductMixServiceImpl implements ProductMixService {
	private static final String BEFORE_JS_MOTHOD ="function priceCalculation() {";
	private static final String AFTER_JS_MOTHOD ="}";
	@Autowired
	private ProductMixDao productMixDao;
	
	@Autowired
	private FanBaseParameterDao fanBaseParameterDao;

	@Override
	public ProductMix getProductTreeById(String pid) {
		ProductMix pm = productMixDao.findOne(pid);
		List<ProductMix> list = getProductChild(pm);
		if(list.size() > 0) {
			pm.setChildren(list);
		}
		return pm;
	}
	
	private List<ProductMix> getProductChild(ProductMix productMix){
		List<ProductMix> childList = new ArrayList<ProductMix>();
		if(StringUtils.isNotBlank(productMix.getPid())) {
			childList = productMixDao.findByPid(productMix.getId());
			for (ProductMix productMix2 : childList) {
				 if (StringUtils.isNotBlank(productMix.getPid())) {
					 productMix2.setChildren(getProductChild(productMix2));
				 }
			}
		}
		if (childList.size() == 0) {
	        return childList;
	    }
		return childList;
		
	}

	@Override
	public void save(ProductMix p, FanBaseParameter f) {
		productMixDao.save(p);
		fanBaseParameterDao.save(f);
		
	}

	@Override
	public void save(ProductMix p) {
		List<ProductMix> list = new ArrayList<ProductMix>();
		String pid = p.getPid();//获取当前节点的父id
		if(!StringUtils.isEmpty(pid)) {
			ProductMix currentT = productMixDao.findOne(pid);
			currentT.setState("closed");
			list.add(currentT);	
		}
		list.add(p);
		productMixDao.save(list);
		
	}

	@Override
	public void fanModelOffer(String modelNumber) {
		double totalPrice = 0;
		ProductMix model = productMixDao.findOne(modelNumber);
		List<ProductMix> list = productMixDao.findByModelNumber(modelNumber);
		for (ProductMix productMix : list) {
			double currentPrice = 0;
			currentPrice = productMix.getDosage()*productMix.getUnitPrice();
			totalPrice+=currentPrice;
			productMix.setPrice(new BigDecimal(currentPrice));
		}
		System.out.println("风机模型总价为"+totalPrice);
		model.setPrice(new BigDecimal(totalPrice));
		list.add(model);
		productMixDao.save(list);
		
	}

}
